//
//  ZYVideoPlayer.m
//  视频播放
//
//  Created by zhangzhenyun on 2018/8/1.
//  Copyright © 2018年 Beijing Youjiu Network. All rights reserved.
//

#import "ZYVideoPlayer.h"
#import "ZYVideoLoadingView.h"
#import "ZYVideoNoNetView.h"
#import "LayoutButton.h"

@interface ZYVideoPlayer ()
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) UIButton *exitBtn;
@property (nonatomic, strong) ZYVideoToolBar *bottomBar;
@property (nonatomic, strong) ZYVideoLoadingView *loadingView;
@property (nonatomic, strong) ZYVideoNoNetView *noNetView;
/** 手机流量按钮 */
@property (nonatomic, strong) LayoutButton *wwanBtn;
@property (nonatomic, strong) UITapGestureRecognizer *tap;

@end

@implementation ZYVideoPlayer
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupViews];
    }
    return self;
}
- (void)setupViews {
    [self.layer addSublayer:self.playerLayer];
    self.backgroundColor = [UIColor blackColor];
    [self addSubview:self.noNetView];
    [self addSubview:self.bottomBar];
    [self addSubview:self.loadingView];
    [self addSubview:self.wwanBtn];
    [self addSubview:self.exitBtn];
    [self setupLayout];
}
- (void)addGesture {
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showOrHidenBar:)];
    [self addGestureRecognizer:self.tap];
}
- (void)showOrHidenBar:(UITapGestureRecognizer *)tap {
    
}
- (void)listenOritaion {
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];
}
- (void)listenNetStatus {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appwillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
}
#pragma mark - target
/** 销毁播放器 */
- (void)destroyPlayer {
    
}
/** 点击流量按钮 */
- (void)wwanClick:(UIButton *)btn {
    
}
#pragma mark - layout
-(void)layoutSubviews {
    [super layoutSubviews];
    self.playerLayer.frame = CGRectMake(0, 0, self.width, self.height);
}
- (void)setupLayout {
    [self.noNetView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    [self.bottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self);
        make.left.and.right.equalTo(self);
        make.height.mas_equalTo(Fix375(55));
    }];
    [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(Fix375(90), Fix375(30)));
        make.center.equalTo(self);
    }];
    [self.wwanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(Fix375(90), Fix375(30)));
        make.center.equalTo(self);
    }];
    CGFloat exitY = iPhoneX ? Fix375(15) + 24 : Fix375(15);
    [self.exitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(Fix375(15));
        make.top.equalTo(self).offset(exitY);
        make.size.mas_equalTo(CGSizeMake(Fix375(44), Fix375(44)));
    }];
}
#pragma mark - getter
- (AVPlayerLayer *)playerLayer {
    if (!_playerLayer) {
        _playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        _playerLayer.backgroundColor = [UIColor blackColor].CGColor;
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;//视频填充模式
    }
    return _playerLayer;
}
- (AVPlayer *)player{
    if (!_player) {
        _player = [AVPlayer playerWithPlayerItem:self.playerItem];
        // 解决8.1系统播放无声音问题，8.0、9.0以上未发现此问题
        AVAudioSession * session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        [session setActive:YES error:nil];
    }
    return _player;
}
- (AVPlayerItem *)playerItem{
    AVPlayerItem *item;
    if ([self.videoUrl rangeOfString:@"http"].location != NSNotFound) {
        item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:[self.videoUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    } else {
        AVAsset *movieAsset = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:self.videoUrl] options:nil];
        item = [AVPlayerItem playerItemWithAsset:movieAsset];
    }
    return item;
}
- (ZYVideoNoNetView *)noNetView {
    if (_noNetView == nil) {
        _noNetView = [[ZYVideoNoNetView alloc] init];
        _noNetView.hidden = YES;
        _noNetView.refreshBlock = ^(UIButton *btn) {
            
        };
    }
    return _noNetView;
}
-(ZYVideoToolBar *)bottomBar {
    if (!_bottomBar) {
        _bottomBar = [[ZYVideoToolBar alloc] init];
        _bottomBar.playOrPauseBlock = ^(UIButton *btn) {
            
        };
        _bottomBar.valueChangeBlock = ^(ZYVideoSlider *slider) {
            
        };
        _bottomBar.finishChangeBlock = ^(ZYVideoSlider *slider) {
            
        };
        _bottomBar.draggingSliderBlock = ^(ZYVideoSlider *slider) {
            
        };
    }
    return _bottomBar;
}
- (ZYVideoLoadingView *)loadingView {
    if (_loadingView == nil) {
        _loadingView = [[ZYVideoLoadingView alloc] init];
    }
    return _loadingView;
}
- (LayoutButton *)wwanBtn {
    if (_wwanBtn == nil) {
        _wwanBtn = [[LayoutButton alloc] init];
        _wwanBtn.layoutType = EButtonLayoutLeftImageRightTitle;
        _wwanBtn.backgroundColor = UIColorFromRGB(0x020202);
        _wwanBtn.layer.cornerRadius = Fix375(15);
        _wwanBtn.layer.masksToBounds = YES;
        _wwanBtn.titleLabel.font = RMFont(12);
        [_wwanBtn setImage:[UIImage imageNamed:@"liuliang"] forState:UIControlStateNormal];
        _wwanBtn.edgeFloat = Fix375(3);
        [_wwanBtn addTarget:self action:@selector(wwanClick:) forControlEvents:UIControlEventTouchUpInside];
        _wwanBtn.hidden = YES;
    }
    return _wwanBtn;
}
- (UIButton *)exitBtn {
    if (_exitBtn == nil) {
        _exitBtn = [[UIButton alloc] init];
//        _exitBtn.layer.opacity = 0.0f;
        _exitBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        _exitBtn.imageEdgeInsets = UIEdgeInsetsMake(-Fix375(14), -Fix375(14), Fix375(0), Fix375(0));
        [_exitBtn setImage:[UIImage imageNamed:@"exitVideoPlay"] forState:UIControlStateNormal];
        [_exitBtn addTarget:self action:@selector(destroyPlayer) forControlEvents:UIControlEventTouchUpInside];
    }
    return _exitBtn;
}
@end
